<template>
  <Container>
    <template v-slot:searchForm>
      <div class="searchRow">
        <el-form class="elForm" ref="form" :model="searchFormData" label-width="80px">
          <el-form-item label="类型名称">
            <el-input v-model="searchFormData.deviceTypeName" clearable placeholder="请输入"></el-input>
          </el-form-item>
          <!-- <el-form-item label="数据类型">
            <el-input v-model="searchFormData.dataType" clearable placeholder="请输入"></el-input>
          </el-form-item> -->
        </el-form>
        <div class="btnList">
          <el-button type="danger" icon="el-icon-delete" @click="handleClickDel(selectionList)"
            :disabled="selectionList.length == 0" plain>删
            除</el-button>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleClickAddEdit('add')" plain>添
            加</el-button>
          <el-button type="primary" icon="el-icon-search" @click="queryTableList" plain>查 询</el-button>
        </div>
      </div>
    </template>
    <template v-slot:table>
      <el-table :data="tableData" border height="100%" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型名称">
        </el-table-column>
        <el-table-column prop="regularExpression" label="正则表达式">
        </el-table-column>
        <el-table-column prop="sort" label="排序">
        </el-table-column>
        <el-table-column label="文件列表" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="handleClickLookView(scope.row)">查看文件</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="handleClickAddEdit('edit', scope.row)">编辑</el-button>
            <el-button type="text" @click="handleClickDel([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <AddEdit :title="'设备类型'" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
      <el-dialog title="文件列表" :visible.sync="lookViewFlag" width="50%">
        <el-table :data="fileList" border>
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="fileName" label="文件名称">
          </el-table-column>
          <el-table-column prop="fileType" label="文件格式" width="200">
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text"
                @click="downloadFile(scope.row.filesId, scope.row.fileName, scope.row)">文件下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="lookViewFlag = false">取 消</el-button>
        </span>
      </el-dialog>

    </template>
    <template v-slot:pagination>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 100, 200, 300, 400, 500, 600]" :page-size="size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </template>
  </Container>
</template>

<script>
import Container from "@/components/Container"
import AddEdit from './components/addEdit';
import deviceType from "@/api/deviceType"
export default {
  components: { Container, AddEdit },
  data() {
    return {
      searchFormData: {},
      tableData: [],
      selectionList: [],
      page: 1,
      size: 100,
      total: 10,
      addEditFlag: 'add',
      dialogVisible: false,
      formData: {},
      fileList: [],
      lookViewFlag: false
    }
  },
  watch: {},
  mounted() {
    this.queryTableList();
  },
  methods: {
    queryTableList() {
      let params = {
        page: this.page,
        size: this.size,
        condition: {
          ...this.searchFormData
        }
      }
      deviceType.queryPageList(params).then(res => {
        let { data } = res
        this.total = data.total;
        this.tableData = data.list;
      }).catch(err => {
        console.log(err)
      })
    },
    closeDialog() {
      this.dialogVisible = false;
      this.formData = {};
      this.queryTableList();
    },
    handleClickLookView(row) {
      let { deviceTypeId } = row;
      this.fileList = [];
      deviceType.queryByDeviceTypeId(deviceTypeId).then(res => {
        console.log(res)
        this.fileList = res.data || [];
        if (this.fileList.length) {
          this.lookViewFlag = true
        } else {
          this.$message.warning('暂无可查看文件')
        }
      })
    },

    async downloadFile(fileId, fileName, row) {
      if (row.iisAddress) {
        window.open(row.iisAddress, '_blank');
        return
      }
      try {
        // 发起GET请求来获取文件  
        this.$notify.info({
          title: '消息',
          message: `${fileName}文件下载中,请稍后! `,
          position: 'bottom-right'
        });
        const response = await files.download(fileId);
        console.log(response)
        this.downLoadFileBlob(response, fileName);
      } catch (error) {
        console.error('下载文件时出错：', error);
      }
    },
    //如果后端返回的是流
    downLoadFileBlob(FileBlob, fileName) {
      const blob = new Blob([FileBlob]);
      console.log(blob)
      // 创建一个隐藏的a标签来下载文件  
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', fileName); // 设置下载文件的名称  
      document.body.appendChild(link);
      link.click(); // 触发下载操作  
      // 清理：移除隐藏的a标签，并释放URL对象  
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);
      this.$notify.success({
        title: '成功',
        message: `${fileName}文件下载成功! `,
        position: 'bottom-right'
      });
    },
    handleClickDel(rowList = []) {
      let list = [];
      rowList.forEach(item => {
        list.push(item.deviceTypeId)
      })
      if (rowList.length == 0) return;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deviceType.delList(list).then(res => {
          if (res.code = 1) {
            this.queryTableList();
            this.$message.success('删除成功')
          } else {
            this.$message.warning('删除失败')
          }
        }).catch(err => {
          this.$message.warning('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClickAddEdit(flag = 'add', row = {}) {
      this.formData = JSON.parse(JSON.stringify(row));
      this.addEditFlag = flag
      this.dialogVisible = true;
    },
    handleSelectionChange(list = []) {
      this.selectionList = list
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryTableList();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryTableList();
    },
  }
}
</script>

<style lang="scss" scoped>
.row {
  padding-bottom: 15px;
}
</style>
